<script setup>
/**
 * & 文件引入区域
 */
import { useRouter } from "vue-router";
import { onActivated, onBeforeMount, onDeactivated, onMounted, ref } from "vue";

import { initMap, getDistance, getLocation } from "@/utils/mapHandle";

import { shopStore } from "@/stores/shop";
import { useUseStore } from "@/stores/user";
import { useIndexStore } from "@/stores/indexStore";

import { selectBgImgList } from "@/server/api/itemApi";
import { getShopInfoList, getShopCategoryTopList, GetelfSupport } from "@/server/api/shopApi";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
/**
 * & 注册区
 */

/**
 * & 变量声明区
 */
const router = useRouter();
let socket = null; // webSocket,与后端进行长连接
let userId = useUseStore().userId; // 用户Id
const clickedOnce = ref(false); // 用来标记点击状态
// 实体店列表接口请求体
let getShopInfoListReq = {
  limit: 20,
  pages: 1,
  categoryId: -1,
  score: false,
  regionId: useUseStore().regionId,
  shopName: "",
};
let ShopPage = ref(); // dom
let playCateData = ref(); // 一级分类区玩的左侧数据
let tagListData = ref(); // 一级分类区右侧的标签列表 3个
let swiperData = ref(); // 轮播图数据
let isRenew = ref(false); // 用于下次回到页面重新更新数据

// 控制分页加载
let loading = ref(false);
let finished = ref(false);

// 图片基础路径
let baseUrl = useUseStore().ing;

/**
 * & 函数区
 */
// 跳转分类页面
const toDetailPageFun = (id) => {
  let path = "";
  let query;

  // 判断传入的分类id，跳转对应的路由
  if (id == "A" || id == "B") {
    path = "/shopCategory";
    query = { id };
  } else if (id == "adfgaergergv") {
    path = "/flight";
  } else if (id == "ergargerge") {
    path = "/hotel";
  } else {
    return;
  }

  router.push({
    path,
    query,
  });
};

// 跳转店详情页面
const toShopDetailFun = (id) => {
  router.push({
    path: "/ShopDetail",
    query: {
      id,
    },
  });
};

// 获取实体店列表数据
const getShopInfoListFun = async () => {
  shopStore().pages = getShopInfoListReq.pages;

  let res = await getShopInfoList(getShopInfoListReq);

  // 图片路径拼接
  res.data.data.list.forEach((item) => {
    // if (item.userImage != null) {
    //   let ImgList = item.userImage.split(".");
    //   item.userImage = baseUrl + ImgList[0] + "_90_100." + ImgList[1];
    // }

    item.coords = [item.localhostLatitude, item.localhostLongitude];
  });

  if (getShopInfoListReq.pages <= 1) {
    // shopStore().shopList = res.data.data;
    const newarr = res.data.data.list.filter((item) => {
      // 确保 item 不为 null
      if (item && item.categoryId) {
        return (
          item.categoryId !== "sdfsd" &&
          item.categoryId !== "fwefw" &&
          item.categoryId !== "dfssd"
        );
      }
      return false; // 如果 item 为 null，则返回 false
    });
    shopStore().shopList = { count: res.data.data.count, list: newarr };
  } else {
    shopStore().shopList.list.push(
      ...res.data.data.list.filter(
        (i) =>
          i.categoryId !== "sdfsd" &&
          i.categoryId !== "fwefw" &&
          i.categoryId !== "dfssd"
      )
    );
  }
  // 计算距离
  await getLocation();
  shopStore().shopList.list.forEach((item) => {
    item.distance = getDistance(item.coords);
  });
  clickedOnce.value = false;
};

// 模糊查询方法
const searchFun = (vl) => {
  // 将关键词赋值给对应字段
  getShopInfoListReq.pages = 1;
  getShopInfoListReq.shopName = vl;

  // 清空数据并且重新请求
  shopStore().shopList = null;
  getShopInfoListFun();

  // 判断是否要在下次进入页面时重新请求
  vl == "" ? (isRenew.value = false) : (isRenew.value = true);
};

// 获取轮播图数据
const selectBgImgListFun = async () => {
  let res = await selectBgImgList(1);
  // res.data.data.forEach((item) => (item.imgUrl = baseUrl + item.imgUrl));
  swiperData.value = res.data.data;
};

// 获取shop首页分类列表
const getShopCategoryList = async () => {
  // 没有数据做首次请求
  if (shopStore().cateListData == null) {
    let res = await getShopCategoryTopList();
    shopStore().cateListData = res.data.data;
  }

  // 左边play数据
  playCateData.value = shopStore().cateListData.filter(
    (item) => item.id == 1
  )[0];
  playCateData.value.content = "shop.category.dine";

  // 右侧列表
  tagListData.value = shopStore().cateListData.filter((item) => item.id != 1);
  tagListData.value[0].content = "shop.category.play";
  tagListData.value[0].sub = "More Fun Here";
  tagListData.value[1].content = "shop.category.flight";
  tagListData.value[1].sub = "Say Go To GO";
  tagListData.value[2].content = "shop.category.hotel";
  tagListData.value[2].sub = "You Can Live Anywhere";


};

// 更新分页方法
const addShopListPage = () => {
  let { limit } = getShopInfoListReq;
  let ReqCount = shopStore().pages * limit;

  if (ReqCount <= shopStore().shopList.count) {
    getShopInfoListReq.pages += 1;
    getShopInfoListFun();

    // 加载状态结束
    loading.value = false;
  } else {
    // 数据全部加载完成
    finished.value = true;
  }
};

// 切换地区修改数据方法
const addressChangeShopDataFun = (id) => {
  // 修改请求体中对应的字段
  getShopInfoListReq.regionId = id;

  // 清空数据并且重新发起请求获取不同地区的数据
  shopStore().shopList = null;
  getShopInfoListFun(); // 获取实体店列表数据
  finished.value = true;
};

// 点击自营店查询出自营店信息列表
const selfSupport = async () => {
  if (!clickedOnce.value) {
    // 第一次点击时调用 GetelfSupport 请求
    shopStore().pages = getShopInfoListReq.pages;

    let res = await GetelfSupport(getShopInfoListReq);

    // 图片路径拼接
    res.data.data.list.forEach((item) => {
      // if (item.userImage != null) {
      //   let ImgList = item.userImage.split(".");
      //   item.userImage = baseUrl + ImgList[0] + "_90_100." + ImgList[1];
      // }

      item.coords = [item.localhostLatitude, item.localhostLongitude];
    });

    if (getShopInfoListReq.pages <= 1) {
      const newarr = res.data.data.list.filter((item) => {
        if (item && item.categoryId) {
          return (
            item.categoryId !== "sdfsd" &&
            item.categoryId !== "fwefw" &&
            item.categoryId !== "dfssd"
          );
        }
        return false;
      });
      shopStore().shopList = { count: res.data.data.count, list: newarr };
    } else {
      shopStore().shopList.list.push(
        ...res.data.data.list.filter(
          (i) =>
            i.categoryId !== "sdfsd" &&
            i.categoryId !== "fwefw" &&
            i.categoryId !== "dfssd"
        )
      );
    }

    // 计算距离
    await getLocation();
    shopStore().shopList.list.forEach((item) => {
      item.distance = getDistance(item.coords);
    });

    // 标记为第一次点击已处理
    clickedOnce.value = true;
  } else {
    // 第二次及之后点击时调用 getShopInfoListFun
    getShopInfoListFun();
  }
};

// 与后端进行长连接
// const connectWebSocket = () => {
//   if (useUseStore().token != "") {
//     const socketUrl = "wss://sea.im/api/dailyActive/" + userId;
//     socket = new WebSocket(socketUrl);

//     socket.onopen = () => {
//       // 在这里执行WebSocket 1连接成功后的逻辑
//     };

//     socket.onmessage = (event) => {
//       // 在这里处理WebSocket 1接收到的消息
//     };

//     socket.onclose = () => {
//       // 在这里执行WebSocket 1连接关闭后的逻辑
//     };
//   }
// };

// 生命周期
onBeforeMount(() => {
  selectBgImgListFun(); // 获取轮播图数据
  getShopCategoryList(); // 获取shop首页分类列表
  // connectWebSocket(); // 与后端进行长连接
});

onActivated(() => {
  // 判断是否为首次请求
  if (!shopStore().shopList) {
    getShopInfoListFun(); // 获取实体店列表数据
  } else {
    // 请求一次判断总数是否更新,如果总数发送变化代表数据发生变化，重新请求赋值到缓存数据
    getShopInfoList(getShopInfoListReq).then(({ data }) => {

      if (data.data.count != shopStore().shopList.count) {
        shopStore().shopList = null;
        getShopInfoListFun(); // 获取实体店列表数据
      }
    });
  }
});

onDeactivated(() => {
  if (isRenew.value) {
    // 清空数据，下次进入页面重新请求
    shopStore().shopList = null;
    getShopInfoListReq.shopName = ""
  }
});

onMounted(() => {
  initMap();
});

</script>

<template>

  <div id="container"></div>

  <div class="ShopPage" ref="ShopPage">
    <!-- 头部 -->
    <div class="top">
      <TopBar :type="1" :isScaner="true" :regionChange="true" @searchFun="searchFun"
        @shopDataChangeFun="addressChangeShopDataFun" />
    </div>

    <!-- 骨架屏 -->
    <van-skeleton-image class="skeleton-img" v-if="!playCateData || !tagListData" />

    <!-- 功能区 -->
    <div class="main">
      <div class="left" v-if="playCateData">
        <div class="title">
          <span>{{ $t(playCateData.content) }}</span>
          <img vue-lazyload src="/images/Shop/shopMainBtn.png" @click="toDetailPageFun(playCateData.categoryId)"
            :class="['btn', useIndexStore().isRtl ? 'is_rtl' : '']" />
        </div>

        <div class="swiper" v-if="swiperData" dir="ltr">
          <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
            <van-swipe-item v-for="item in swiperData" :key="item.contentId">
              <img alt="" vue-lazyload v-lazy="item.imgUrl" @click="toShopDetailFun(item.contentId)" />
            </van-swipe-item>
          </van-swipe>
          <div class="mask"></div>
          <div class="mask"></div>
        </div>
      </div>

      <div class="right" v-if="tagListData">
        <div :style="{
          backgroundImage: `url('/images/Shop/main${i + 2}.png')`,
        }" @click="toDetailPageFun(item.categoryId)" v-for="(item, i) in tagListData" :key="item.categoryId"
          class="item">
          <div class="title">
            <span>{{ $t(item.content) }}</span>
            <img :class="['btn', useIndexStore().isRtl ? 'is_rtl' : '']" src="/images/Shop/shopMainBtn.png" vue-lazyload
              alt="" />
          </div>

          <div class="sub">{{ item.sub }}</div>
        </div>
      </div>
    </div>

    <!-- 切换按钮 -->
    <div class="switch-button" @click="selfSupport">
      <img src="/public/images/weizhi.png" id="clickable-image" alt="PiPayShop Logo">
    </div>

    <!-- 骨架屏 -->
    <div class="skeleton" v-if="!shopStore().shopList">
      <van-skeleton class="skeleton-text" title :row="5" />
      <van-skeleton class="skeleton-text" title :row="5" />
    </div>

    <!-- shopList -->
    <div class="shopList" v-if="shopStore().shopList && shopStore().shopList.list.length">
      <div class="list">
        <van-list :finished-text="$t('shop.shopList.finish')" v-model:loading="loading" @load="addShopListPage"
          :finished="finished">
          <div class="item" v-for="item in shopStore().shopList.list" :key="item.shopId">
            <div :class="['img', useIndexStore().isRtl ? 'is_rtl' : '']">
              <img :src="item.userImage || `/images/pipayshop_logo.png`" vue-lazyload />
              <div class="PiLogo" v-show="item.membership">
                <span> {{ item.piratio }}</span>
              </div>
            </div>

            <div class="right" @click="toShopDetailFun(item.shopId)">
              <div class="title">
                {{ item.shopName || $t("shop.shopList.noData") }}
              </div>

              <div class="sub">
                {{ item.shopIntroduce || $t("shop.shopList.noData") }}
              </div>

              <div class="distance">
                {{ item.distance || $t("shop.shopList.noPosition") }}
              </div>

              <div :class="['btn', useIndexStore().isRtl ? 'is_rtl' : '']" @click="toShopDetailFun(item.shopId)">
                {{ $t("shop.enter") }}
              </div>
            </div>
          </div>
        </van-list>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.skeleton-img {
  width: 300rem;
  height: 300rem;
  margin: 30rem auto;
}

.ShopPage {
  min-height: 100vh;
  max-height: 100vh;
  overflow-y: scroll;

  &::-webkit-scrollbar {
    display: none;
  }

  .top {
    padding: 0 2rem;
  }

  .main {
    padding: 0 16rem;
    display: flex;
    justify-content: space-between;

    >.left {
      border-radius: 12rem;
      padding: 8rem 12rem 16rem;
      background: url("/images/Shop/main1.png") no-repeat 50% 17%;
      background-size: 112% 108%;
      width: 173rem;
      height: 256rem;
      box-sizing: border-box;
      box-shadow: 1rem 5rem 10rem -5rem rgba(0, 0, 0, 0.3);

      >.title {
        font-size: 24rem;
        font-weight: 600;
        line-height: 34rem;
        color: #ffffff;

        display: flex;
        justify-content: space-between;
        align-items: center;

        margin-bottom: 10rem;

        >.btn.is_rtl {
          transform: rotate(180deg);
        }
      }

      >.swiper {
        position: relative;
        width: 140rem;
        border-radius: 12rem;

        margin-right: 8rem;

        >.my-swipe {
          position: relative;
          z-index: 120;
          height: 188rem;

          .van-swipe-item {
            width: 100%;

            img {
              width: 100%;
              margin-top: 21px;
              border-radius: 20px;
              height: auto;
              object-fit: cover;
            }
          }

          :deep(.van-swipe__indicators) {
            bottom: 0rem;
            left: 54%;
            width: max-content;

            >.van-swipe__indicator--active {
              border-radius: 3rem;
              padding: 0 5rem;
            }
          }
        }

        >.mask {
          position: absolute;
          right: -5rem;
          top: -10rem;
          z-index: 100;
          width: 6rem;

          height: 100%;
          border-bottom-right-radius: 8rem 30rem;
          border-top-right-radius: 8rem 30rem;
          background: #333333;
          transform: scaleY(0.8);

          &:last-of-type {
            transform: scaleY(0.7);
            right: -10rem;
            background: #666666;
            z-index: 90;
          }
        }
      }
    }

    >.right {
      width: 173rem;

      display: flex;
      flex-direction: column;
      justify-content: space-between;

      >.item {
        background-size: 110%;
        background-repeat: no-repeat;
        background-position: 50% 15%;

        border-radius: 12rem;
        box-shadow: 1rem 5rem 10rem -5rem rgba(0, 0, 0, 0.3);

        padding: 12rem 10rem 20rem 12rem;

        color: #fff;

        img {
          object-fit: contain;
        }

        .title {
          font-size: 20rem;
          line-height: 28rem;
          font-weight: 500;

          display: flex;
          align-items: center;
          justify-content: space-between;

          >.btn.is_rtl {
            transform: rotate(180deg);
          }
        }

        .sub {
          font-size: 14rem;
          font-weight: 400;
          line-height: 20rem;
        }
      }
    }
  }

  .skeleton {
    padding-top: 20rem;

    >div {
      margin-bottom: 20rem;
    }
  }

  .shopList {
    padding-bottom: 45rem;

    >.top {
      position: sticky;
      top: 0;
      padding-top: 16rem;
      background: #fff;

      z-index: 100;

      box-shadow: 0rem 5rem 15rem -5rem rgba(0, 0, 0, 0.1);
    }

    .list {
      padding: 0 16rem;
      margin-top: 16rem;

      .item {
        display: flex;
        padding: 8rem;
        margin-bottom: 8rem;
        border-radius: 8rem;
        box-shadow: 0rem 5rem 15rem #cec7d422;
        position: relative;

        >.img {
          width: 64rem;
          height: 74rem;
          margin-right: 12rem;
          border-radius: 8rem;
          overflow: hidden;

          flex-shrink: 0;

          position: relative;

          &.is_rtl {
            margin-left: 12rem;
            margin-right: 0;
          }

          >img {
            width: 100%;
            height: 100%;
          }

          >.PiLogo {
            position: absolute;
            left: 0;
            top: 0;

            padding: 1rem 6rem;

            font-size: 12rem;
            font-weight: 200;
            line-height: 20rem;
            color: #fff;

            background: #642e8e;
            border-radius: 8rem 0rem 8rem 0rem;
          }
        }

        >.right {
          color: #999999;
          font-weight: 400;
          font-size: 13rem;
          line-height: 18rem;

          flex: 1;
          max-width: 266rem;
          display: flex;
          flex-wrap: wrap;
          position: relative;

          >div {
            width: 100%;
          }

          >.title {
            width: 80%;
            font-weight: 500;
            line-height: 22rem;
            color: #333333;
            font-size: 16rem;
            margin-bottom: 2rem;
          }

          >.sub {
            width: 55%;

            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }

          >.distance {
            max-width: 80%;
            display: flex;
            align-self: flex-end;
          }

          >.btn {
            line-height: 16rem;
            padding: 6rem 15rem;
            color: #642e8e;
            border: 1rem solid #642e8e;
            border-radius: 8rem;

            width: max-content;
            position: absolute;
            right: 0rem;
            bottom: 0rem;

            &.is_rtl {
              left: 0;
              right: unset;
            }
          }
        }
      }
    }
  }
}

.switch-button {
  text-align: right;
  /* 设置文本/内联元素（如这里的button）居右 */
  margin: 10px 30px 10px 0;
  /* 上下间距各20px，左右间距默认为0 */
}

.switch-button img {
  width: 35px;
  /* 将图片宽度设置为10px */
  height: 35px;
  /* 将图片高度设置为10px */
  cursor: pointer;
  /* 鼠标悬停时显示为手型指针 */
  transition: transform 0.2s;
  /* 添加过渡效果，使点击效果更平滑 */
}

.switch-button img:active {
  transform: scale(0.9);
  /* 点击时缩小图片 */
}
</style>
